package com.shushan.home;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.BaseHomeFragment;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.home.adapter.AppUseTimeAdapter;
import com.shushan.home.adapter.ExRecordAdapter;
import com.shushan.home.bean.RecordBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.setting.ParentSettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomRoundProgressView;
import com.shushan.ui.OffsetRecyclerDivider;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.ControlUtil;
import com.shushan.util.DateUtils;
import com.shushan.util.DensityUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;

/**
 * @ClassName: RecordFragment
 * @Desciption: 记录fragment界面
 * @author: yichaohua
 * @date: 2018-09-12
 */
public class RecordFragment extends BaseHomeFragment implements View.OnClickListener,AdapterView.OnItemClickListener, VerificationCodeView.OnCodeFinishListener {

    private static final String TAG = "RecordFragment";

    private CustomRoundProgressView totalRightRateView;
    private GridView gvExRecord;
    private RecyclerView rvAppUseTime;
    private LinearLayout llDetail;
    private TextView tvTodayDate;
    private TextView tvTotalExTopic;
    private TextView tvExCount;
    private TextView tvGetUseTime;
    private TextView tvRightRate;
    private TextView tvNoRecord;
    private TextView tvRightGrade;
    private TextView remainTimeText;
    private Button startGameButton;
    private LinearLayout gradeLayout;
    private VerificationCodeView veriCodeView;
    private Dialog changeToParentDialog;
    private FingerprintIdentify mFingerprintIdentify;

    private BabyApplication babyApplication = BabyApplication.getInstance();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_record, null);
        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,getActivity())){
            view.findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }
        initView(view);

        getData();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        tvRightGrade.setText(ToolUtils.getLevelTermText(babyApplication.getCurrentChildBean()));
        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + babyApplication.getCurrentChildId());
        remainTimeText.setText(gameTime + "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(changeToParentDialog != null){
            changeToParentDialog.dismiss();
        }

        if(mFingerprintIdentify != null){
            mFingerprintIdentify.cancelIdentify();
        }
    }

    private void initView(View view){
        remainTimeText = view.findViewById(R.id.record_remain_time_tv);
        gradeLayout = view.findViewById(R.id.actionbar_right_grade_layout);
        gradeLayout.setOnClickListener(this);
        totalRightRateView = view.findViewById(R.id.crpv_total_right_rate);
        totalRightRateView.setMax(100);
        gvExRecord = view.findViewById(R.id.gv_record);
        gvExRecord.setOnItemClickListener(this);
        startGameButton = view.findViewById(R.id.record_start_game_btn);
        startGameButton.setOnClickListener(this);
        rvAppUseTime = view.findViewById(R.id.rv_app_use_time);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvAppUseTime.setLayoutManager(linearLayoutManager);
        rvAppUseTime.addItemDecoration(new OffsetRecyclerDivider(DensityUtil.dip2px(getActivity(),14.5f)));
        llDetail = view.findViewById(R.id.ll_detail);
        llDetail.setOnClickListener(this);
        tvTodayDate = view.findViewById(R.id.tv_today_date);
        tvTodayDate.setText(DateUtils.getNowDate("yyyy-MM-dd"));
        tvTotalExTopic = view.findViewById(R.id.tv_total_ex_topic);
        tvExCount = view.findViewById(R.id.tv_ex_count);
        tvGetUseTime = view.findViewById(R.id.tv_get_use_time);
        tvRightRate = view.findViewById(R.id.tv_right_rate);
        tvNoRecord = view.findViewById(R.id.tv_no_record);
        tvRightGrade = view.findViewById(R.id.actionbar_right_grade_tv);
    }

    private void getData(){
        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(getActivity(), UrlConst.BASE_URL).appendRegion(UrlConst.RECORD_ITEM);
        UrlParse paramParse = new UrlCommParse(getActivity())
                .putValue("child_id",childId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<RecordBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(RecordBean recordBean) {
                        setData(recordBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setData(RecordBean recordBean){
        if(recordBean == null){
            return;
        }

        tvTotalExTopic.setText("共练习"+recordBean.today_exercises_num+"题");
        tvExCount.setText("练习"+recordBean.today_answer_num+"次");
        tvGetUseTime.setText("共获得"+DateUtils.getHour(recordBean.today_play_time)+"小时手机使用时间");
        int rightRate = 0;
        float rate = ((float)recordBean.today_right_num/ recordBean.today_exercises_num*100);
        if(rate > 0 && rate < 1){
            rightRate = 1;
        }else{
            rightRate = (int)rate;
        }
        totalRightRateView.setProgress(rightRate);
        tvRightRate.setText(rightRate+"%");
        rvAppUseTime.setAdapter(new AppUseTimeAdapter(recordBean.getPlayListBeans(),recordBean.today_play_time));
        if(recordBean.getPlayListBeans().size() == 0){
            tvNoRecord.setVisibility(View.VISIBLE);
        }
        gvExRecord.setAdapter(new ExRecordAdapter(recordBean.getRecordListBeans()));
        tvRightGrade.setText(ToolUtils.getLevelTermText(babyApplication.getCurrentChildBean()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_detail:
                startActivity(StudyStatisticsActivity.class);
                break;
            case R.id.actionbar_right_grade_layout:
                showToParentDialog();
                break;
            case R.id.record_start_game_btn:
                startGame();
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(),StudyStatisticsActivity.class);
        intent.putExtra("position",position);
        startActivityAllow(intent);
    }

    @Override
    public void onFragmentChecked() {
        getData();
    }

    @Override
    public void onFragmentHided() {

    }

    private void showToParentDialog() {
        if (changeToParentDialog == null){
            changeToParentDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
            changeToParentDialog.setContentView(R.layout.change_to_parent_dialog);
            changeToParentDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

            veriCodeView = changeToParentDialog.findViewById(R.id.verification_code_view);
            veriCodeView.setOnCodeFinishListener(this);
            Button coloseButton = changeToParentDialog.findViewById(R.id.btn_cancel);
            coloseButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeToParentDialog.dismiss();
                    if(mFingerprintIdentify != null){
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            changeToParentDialog.setCancelable(false);
        }

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        ImageView parentImg = changeToParentDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = changeToParentDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = changeToParentDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            ((TextView)changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请验证指纹或者家长密码去设置");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    startActivity(ParentSettingActivity.class);
                    changeToParentDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            ((TextView)changeToParentDialog.findViewById(R.id.parent_dialog_tv)).setText("请输入家长密码去设置");
        }

        if(veriCodeView != null){
            veriCodeView.clear();
        }

        if(!changeToParentDialog.isShowing()){
            changeToParentDialog.show();
        }
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            if(changeToParentDialog != null){
                changeToParentDialog.dismiss();
            }

            startActivity(ParentSettingActivity.class);
        }else {
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }
        }
    }

    private void startGame() {
        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + babyApplication.getCurrentChildId());
        if(gameTime > 0){
            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
            if(isChildControl){
                ControlUtil.gotoGamesFloat(getActivity());
            }else {
                Intent intent= new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivityAllow(intent);

                showToast("返回桌面成功");
            }
        }else {
            showToast("无娱乐时间，赶快去练习吧");
        }
    }
}
